package com.zhu.queue.impl;

import com.zhu.linkedlist.MyLinkedList;
import com.zhu.queue.Queue;

/**
 * 基于链表实现的队列
 * @author: zhu
 * @date: 2019/1/13 15:12
 */
public class LinkedListQueue<E> implements Queue<E> {

    private class Node {
        public E e;//存放的元素
        public Node next;//下一个节点
        public Node(E e, Node next) {
            this.e = e;
            this.next = next;
        }
        public Node(E e) {
            this(e, null);
        }
        public Node() {
            this(null, null);
        }
        @Override
        public String toString() {
            return e.toString();
        }
    }

    private Node head,tail;//头节点和尾节点
    private int size;//元素个数

    public LinkedListQueue(){
        head = null;
        tail = null;
        size = 0;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    /** 入队，在链表的尾部进行操作 */
    @Override
    public void enqueue(E e) {
        if (tail == null){
            tail = new Node(e);
            head = tail;
        }else {
            tail.next = new Node(e);
            tail = tail.next;
        }
        size ++;
    }

    /** 出队，在链表头操纵 */
    @Override
    public E dequeue() {
        if (isEmpty()){
            throw new IllegalArgumentException("队列为空");
        }
        Node delNode = head;
        head = head.next;
        delNode.next = null;
        if (head == null){
            tail = null;
        }
        size --;
        return delNode.e;
    }

    @Override
    public E getFront() {
        if (isEmpty()){
            throw new IllegalArgumentException("队列为空");
        }
        return head.e;
    }

    @Override
    public String toString(){
        StringBuilder res = new StringBuilder();
        res.append("queue:front ");
        Node cur = head;
        while (cur != null){
            res.append(cur + "--> ");
            cur = cur.next;
        }
        res.append("NULL  tail");
        return res.toString();
    }
}
